package com.ywh.composetest.activity

import android.os.Bundle
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.ywh.composetest.toastShort
import com.ywh.composetest.widget.BoxTextCompose
import kotlinx.coroutines.launch
import java.util.Random

/**
 * key:
 *  1.key:返回Any,但是要能被bundle存储的类型。如果是对象，必须要序列化，否则崩溃
 *  2.指定key之后，在添加一个item时如果这个item的key在列表已存在 就会崩溃
 * contentType:
 *
 * todo 为啥修改一个item,屏幕上所有item都重组了？
 */

class LazyColumnActivity : BaseComposeActivity() {
    private val TAG = LazyColumnActivity::class.java.simpleName


    @Stable
    data class ItemData(val id: Int, @Stable var name: String)

    @OptIn(ExperimentalLayoutApi::class, ExperimentalFoundationApi::class)
    @Composable
    override fun OnComposable(savedInstanceState: Bundle?) {
        val list = remember {
            mutableStateListOf<ItemData>()
        }

        val coroutineScope = rememberCoroutineScope()
        val lazyColumnState = rememberLazyListState()

        LaunchedEffect(Unit) {
            for (i in 0..50) {
                list.add(ItemData(i, "Item:${i}"))
            }
        }
        Log.e(TAG, "OnComposable")

        Column {
            FlowRow(
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                BoxTextCompose(content = "添加不存在的id-ok") {
                    list.add(0, ItemData(10000, "id不同"))
                }

                BoxTextCompose(content = "添加已存在的id-崩溃") {
                    list.add(0, ItemData(list[0].id, "第一个item的id"))
                }

                BoxTextCompose(content = "删除第一个") {
                    list.removeFirst()
                }

                BoxTextCompose(content = "修改第一个生效") {
                    val first = list[0]
                    list[0] = first.copy(id = first.id, name = "修改后的1")
                }

                BoxTextCompose(content = "修改第一个不生效") {
                    val first = list[0]
                    first.name = "修改后的2"
                    list[0] = first
                }

                BoxTextCompose(content = "LazyListState相关api") {
                    //当前页面列表显示的第一项下标
                    val firstVisibleItemIndex = lazyColumnState.firstVisibleItemIndex
                    Log.e(TAG, "firstVisibleItemIndex:${firstVisibleItemIndex}")

                    //当前页面列表显示第一项的滑动偏移量
                    val firstVisibleItemScrollOffset = lazyColumnState.firstVisibleItemScrollOffset
                    Log.e(TAG, "firstVisibleItemScrollOffset:${firstVisibleItemScrollOffset}")

                    //当列表被拖拽时候,会触发对应的分发事件,interactionSource存放着相关的事件state
                    val interactionSource = lazyColumnState.interactionSource
                    Log.e(TAG, "interactionSource:${interactionSource}")

                    //列表布局相关信息
                    val layoutInfo = lazyColumnState.layoutInfo
                    Log.e(TAG, "layoutInfo:${layoutInfo}")

                    //标识当前列表是否处于滑动状态
                    val isScrollInProgress = lazyColumnState.isScrollInProgress
                    Log.e(TAG, "isScrollInProgress:${isScrollInProgress}")
                }
                BoxTextCompose(content = "scrollToItem(5)") {
                    coroutineScope.launch {
                        lazyColumnState.scrollToItem(5, 0)
                    }
                }
                BoxTextCompose(content = "animateScrollToItem(10)") {
                    coroutineScope.launch {
                        lazyColumnState.animateScrollToItem(10, 0)
                    }
                }
                BoxTextCompose(content = "Items的Key，contentType") {

                }
            }

            Box(
                modifier = Modifier
                    .background(Color.Gray)
                    .fillMaxWidth()
                    .height(10.dp)
            ) {

            }
            Log.e(TAG, "LazyColumn")

            OnLazyColumn(list, lazyColumnState)
        }

    }

    @OptIn(ExperimentalFoundationApi::class)
    @Composable
    private fun OnLazyColumn(list: List<ItemData>, lazyColumnState: LazyListState) {
        Log.e(TAG, "OnLazyColumn")
        LazyColumn(
            modifier = Modifier.fillMaxSize(),
            state = lazyColumnState,
            contentPadding = PaddingValues(horizontal = 2.dp, vertical = 3.dp),//内间距
            reverseLayout = false,
            verticalArrangement = Arrangement.spacedBy(8.dp),//item间距
            userScrollEnabled = true
        ) {
                stickyHeader {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(50.dp)
                            .background(Color.White)
                    ) {
                        Text(text = "这是一个StickyHeader")
                    }
                }
//                //添加单个
                item {
                    ItemCompose(ItemData(9900,"item单独添加")) {
                        toastShort("点击item")
                    }
                }
//
                item {
                    LazyRowCompose()
                }
//
                stickyHeader {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(50.dp)
                            .background(Color.White)
                    ) {
                        Text(text = "这也是一个StickyHeader")
                    }
                }
//                //添加指定数量
//                items(3) { index ->
//                    ItemCompose("Items with index:${index}") {
//                        toastShort("点击position:${index}")
//                    }
//                }
//                添加list
            items(list, key = {
                it.id
            }, contentType = {
                it::class.java.hashCode()
            }) {

                Log.e(TAG, "list.hashCode():${list.hashCode()},${list.toList().hashCode()}")
                Log.e(TAG, "list.2:${list.get(2).hashCode()}")
                ItemCompose(it) {
                    toastShort("点击:${it}")
                }
            }
//
//            items(list.size, key = {
//                list[it].id
//            }) { index ->
//                Log.e(TAG, "list.hashCode():${list.hashCode()},${list.toList().hashCode()}")
//                Log.e(TAG, "list.2:${list.get(2).hashCode()}")
//
//                ItemCompose(list[index]) {
//                    toastShort("点击:")
//                }
//            }
        }
    }

    @Composable
    private fun LazyRowCompose() {
        val list = remember {
            mutableStateListOf<String>()
        }
        for (i in 0..20) {
            list.add("RowItem:${i}")
        }
        LazyRow {
            itemsIndexed(list, key = { _, item ->
                item
            }) { index, item ->
                var red by remember {
                    mutableIntStateOf(Random().nextInt(255))
                }
                var green by remember {
                    mutableIntStateOf(Random().nextInt(255))
                }
                var blue by remember {
                    mutableIntStateOf(Random().nextInt(255))
                }
                Box(
                    modifier = Modifier
                        .size(100.dp, 50.dp)
                        .background(Color(red = red, green = green, blue = blue, alpha = 255))
                ) {
                    Text(text = item)
                }
            }
        }
    }

    @Composable
    private fun ItemCompose(content: ItemData, onItemClick: () -> Unit) {
//        var red by remember {
//            mutableIntStateOf(Random().nextInt(255))
//        }
//        var green by remember {
//            mutableIntStateOf(Random().nextInt(255))
//        }
//        var blue by remember {
//            mutableIntStateOf(Random().nextInt(255))
//        }
        SideEffect {
            Log.e(TAG, "ItemCompose:重组重组")
        }

        Row {
            Log.e(TAG, "ItemCompose:")
            Text(text = content.name)
        }
//        Box(
//            modifier = Modifier
//                .fillMaxWidth()
//                .height(44.dp)
//                .clickable {
//                    onItemClick.invoke()
//                },
//            contentAlignment = Alignment.CenterStart
//        ) {
//            Text(text = name)
//        }

    }

}